package de.tum.in.eist.poll.client.views;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.in.eist.poll.client.controllers.Controller;
import de.tum.in.eist.poll.client.views.widgets.evaluations.QuestionSingleChoiceEvaluationWidget;
import de.tum.in.eist.poll.client.views.widgets.evaluations.QuestionTextEvaluationWidget;
import de.tum.in.eist.poll.shared.beans.Answer;
import de.tum.in.eist.poll.shared.beans.Feedback;
import de.tum.in.eist.poll.shared.beans.Question;
import de.tum.in.eist.poll.shared.beans.SingleChoiceAnswer;
import de.tum.in.eist.poll.shared.beans.SingleChoiceQuestion;
import de.tum.in.eist.poll.shared.beans.TextAnswer;
import de.tum.in.eist.poll.shared.beans.TextQuestion;

/**
 * The Evaluation page
 * @author Sebastian Hofstetter
 * 
 */
public class EvaluationView extends View {

	private VerticalPanel evaluationPanel = new VerticalPanel();

	public EvaluationView() {
		// only shows evaluation data if there is a lecture accessable
		if (Controller.controller.getCurrentLectureId() != null) {
			// requests the feedback data to the current lecture
			Controller.evaluationController.getFeedback(new AsyncCallback<List<Feedback>>() {
				@Override
				public void onSuccess(List<Feedback> result) {
					Question[] questions = Controller.controller.getQuestions();
					Feedback[] feedback = new Feedback[result.size()];
					result.toArray(feedback);

					ArrayList<Answer> answers = new ArrayList<Answer>();	// the answers to the current question
					// evaluates all answers, which are assigned to the lecture
					for (int i = 0; i < questions.length; i++) {
						for (Feedback f : feedback) {
							answers.add(f.getAnswers()[i]);
						}
						Question q = questions[i];

						if (q instanceof SingleChoiceQuestion) {
							SingleChoiceAnswer[] a= new SingleChoiceAnswer[answers.size()];
							answers.toArray(a);
							evaluationPanel.add(new QuestionSingleChoiceEvaluationWidget(a, (SingleChoiceQuestion) q));
						} else if (q instanceof TextQuestion) {
							TextAnswer[] a = new TextAnswer[answers.size()];
							answers.toArray(a);
							evaluationPanel.add(new QuestionTextEvaluationWidget(a, (TextQuestion) q));
						}
						answers.clear();
					}
				}

				@Override
				public void onFailure(Throwable caught) {
				}
			});
		}

		initWidget(evaluationPanel);
		evaluationPanel.addStyleName("evaluationView");
	}
}
